package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import model.UserInfo;
import util.AppVar;
import util.DBUtils;
import util.ResultUtil;
import util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * 修改文章
 */
@WebServlet("/upart")
public class UpdateArticleServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String msg = "未知错误！";
        int data = 0;
        //登录权限校验
        UserInfo userInfo = SessionUtils.getLoginUser(req);
        if (userInfo != null) {
            //得到前段的值并校验
            String title = req.getParameter("title");
            String context = req.getParameter("context");
            String aidStr = req.getParameter("aid");
            if (!StrUtil.isBlank(aidStr) && !StrUtil.isBlank(context)&&!StrUtil.isBlank(title)) {//参数正常
                int aid=Integer.valueOf(aidStr);
                if(aid>0){
                    //2.执行数据库的修改
                    Connection connection=DBUtils.getConnection();
                    String sql="update article set title=?,context=? where aid=? and uid=?";
                    PreparedStatement statement=connection.prepareStatement(sql);
                    statement.setString(1,title);
                    statement.setString(2,context);
                    statement.setInt(3,aid);
                    statement.setInt(4,userInfo.getUid());
                    data=statement.executeUpdate();
                    //关闭资源
                    DBUtils.close(null,statement,connection);
                    msg="";
                }else{
                    msg="参数中文章id有误！";
                }
            }else{
                msg="参数不全！";
            }
        }else{
            msg="请先登录！";
        }
        //3.将结果返回给前端
        resp.setContentType(AppVar.RESPONSE_CONTENTTYPE_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtil.toResult(
                200,data,msg)));
    }
}
